package jrain.fw.http.tomcat;

import java.util.concurrent.atomic.AtomicBoolean;

import jrain.fw.core.business.BusinessConst;
import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.service.DestroyService;
import jrain.fw.core.service.InitService;
import jrain.fw.core.service.Service;
import jrain.fw.core.service.ServiceConst;
import jrain.fw.http.common.consts.HttpConsts;

@Service(name = "tomcat", group = HttpConsts.S_HTTP_SERVER_SERVICE, module = ServiceConst.M_HTTP_SERVER, server = true)
public class HttpTomcatService implements InitService, DestroyService {

	private static final Logger log = LoggerFactory.getLogger(HttpTomcatService.class);
	private static final AtomicBoolean init = new AtomicBoolean(false);
	private static volatile HttpTomcatServer server;

	@Override
	public void init() {
		if (!init.getAndSet(true)) {
			server = new HttpTomcatServer();
			new Thread(() -> {
				try {
					server.start();
				} catch (Throwable t) {
					log.error(BusinessConst.LOG_BOOT_REQUEST,HttpConsts.S_HTTP_SERVER_SERVICE + " tomcat start error!", t);
				}
			}).start();
		}
	}

	@Override
	public void destroy() {
		if (init.get()) {
			try {
				if (server != null) {
					server.stop();
				}
				log.info(BusinessConst.LOG_BOOT_REQUEST,"{} tomcat stoped!", HttpConsts.S_HTTP_SERVER_SERVICE);
			} catch (Throwable t) {
				log.error(BusinessConst.LOG_BOOT_REQUEST,HttpConsts.S_HTTP_SERVER_SERVICE + " tomcat stop error!", t);
			}
		}
	}

}
